var express = require('express');
var router = express.Router();
let {UserModel,Dynamics,conver,known} = require('../db/index')
const alipaySdk = require('../alipay')
const AlipayFormData = require('alipay-sdk/lib/form').default
const axios = require("axios");
// PayPal SDK
const paypal = require('@paypal/checkout-server-sdk');
// 文件上传相关
const multer = require('multer');
const path = require('path');
const fs = require('fs');

// 设置文件上传存储
const storage = multer.diskStorage({
  destination: function (req, file, cb) {
    const uploadDir = path.join(__dirname, '../public/uploads/avatars');
    // 确保目录存在
    if (!fs.existsSync(uploadDir)) {
      fs.mkdirSync(uploadDir, { recursive: true });
    }
    cb(null, uploadDir);
  },
  filename: function (req, file, cb) {
    // 生成唯一的文件名
    const uniqueFileName = Date.now() + '-' + Math.round(Math.random() * 1E9) + path.extname(file.originalname);
    cb(null, uniqueFileName);
  }
});

// 创建上传中间件
const upload = multer({ 
  storage: storage,
  limits: { fileSize: 5 * 1024 * 1024 }, // 限制5MB
  fileFilter: function (req, file, cb) {
    // 检查文件类型
    if (file.mimetype.startsWith('image/')) {
      cb(null, true);
    } else {
      cb(new Error('只允许上传图片文件!'), false);
    }
  }
}).single('avatar');

// 创建PayPal环境 - 明确使用沙箱环境
function environment() {
  // 使用沙箱环境 - 这是PayPal的测试环境，不会产生真实交易
  // 使用提供的沙箱商业账户作为商家账户
  let clientId = 'AQIGODiYK4Tq4ST6OUDjXTfDeo1R6_eNgS261ElAaK2i-oVSoAQJLkzaRhPVLcy31i_SvkTZ1G_CYt80'; 
  let clientSecret = 'EI33hbecsKH5Kv9q7dZmNdheSCGldVPRUJyKxtNEAvR4L7rycz93aA7n6URhs1M0IoOTzkr8hICURhtM';
  
  // 商家账户: sb-bt7104406770@business.example.com
  
  // 明确使用沙箱环境配置
  return new paypal.core.SandboxEnvironment(clientId, clientSecret);
}
// 创建PayPal客户端
function client() {
  return new paypal.core.PayPalHttpClient(environment());
}

router.get('/index',async function(req, res, next) {
  let id = req.query.id
  let data = await UserModel.find({_id:id})
  res.send({
    data:data[0]
  })
});
// 支付接口
router.post('/api/alipay/create', async (req, res) => {
  try {
    // 从请求中获取数据
    const { amount, userId } = req.body;

    if (!amount || parseFloat(amount) <= 0) {
      return res.json({
        code: 400,
        success: false,
        message: '金额无效'
      });
    }

    // 生成订单号
    const orderId = 'YC' + Date.now() + Math.floor(Math.random() * 1000);
    const price = parseFloat(amount).toFixed(2);
    const name = '洋币充值';

    const formData = new AlipayFormData();
    formData.setMethod("get");

    const bizContent = {
      out_trade_no: orderId,
      product_code: "FAST_INSTANT_TRADE_PAY",
      total_amount: price,
      subject: name,
      body: `充值${price}元人民币，获得${parseFloat(price) * 10}洋币`,
      passback_params: encodeURIComponent(userId || '') // 传递用户ID参数
    };
    formData.addField("bizContent", bizContent);

    // 配置支付成功和失败的返回页面
    const frontendUrl = "http://localhost:5173/my"; // 前端支付页面地址
    formData.addField("returnUrl", frontendUrl);

    const payUrl = await alipaySdk.exec(
      "alipay.trade.wap.pay",
      {},
      { formData }
    );

    res.json({
      code: 200,
      success: true,
      data: {
        orderId,
        payUrl
      },
      message: '创建订单成功'
    });
  } catch (error) {
    console.error('创建支付订单失败:', error);
    res.json({
      code: 500,
      success: false,
      message: '创建订单失败',
      error: error.message
    });
  }
});

// 支付宝异步通知接口
router.post('/api/alipay/notify', async function(req, res, next) {
  try {
    const data = req.body;
    console.log('支付宝回调数据:', data);
    
    // 验证签名
    const signVerified = true; // 在生产环境中需要真正验证签名
    
    if (signVerified) {
      // 验证成功
      const tradeStatus = data.trade_status;
      
      if (tradeStatus === 'TRADE_SUCCESS' || tradeStatus === 'TRADE_FINISHED') {
        // 支付成功，更新用户洋币
        const outTradeNo = data.out_trade_no; // 订单号
        const totalAmount = parseFloat(data.total_amount); // 支付金额
        const userId = data.passback_params ? decodeURIComponent(data.passback_params) : null; // 解码用户ID
        
        // 计算获得的洋币数量
        const yangcoinAmount = totalAmount * 10;
        
        // 更新用户洋币余额
        if (userId) {
          try {
            await UserModel.findByIdAndUpdate(userId, { $inc: { yangcoin: yangcoinAmount } });
            console.log(`用户 ${userId} 洋币增加 ${yangcoinAmount}`);
          } catch (err) {
            console.error('更新用户洋币失败:', err);
          }
        }
        
        // 响应支付宝
        res.send('success');
      } else {
        res.send('fail');
      }
    } else {
      // 验证失败
      res.send('fail');
    }
  } catch (error) {
    console.error('支付回调处理失败:', error);
    res.send('fail');
  }
});

// 查询支付结果
router.get('/api/alipay/query', async (req, res) => {
  try {
    const { orderId } = req.query;

    if (!orderId) {
      return res.json({
        code: 400,
        success: false,
        message: '订单号不能为空'
      });
    }

    const formData = new AlipayFormData();
    formData.setMethod("get");

    const bizContent = {
      out_trade_no: orderId
    };
    formData.addField("bizContent", bizContent);

    const queryUrl = await alipaySdk.exec(
      "alipay.trade.query",
      {},
      { formData }
    );

    try {
      const { data } = await axios.get(queryUrl);
      res.json({
        code: 200,
        success: true,
        data,
        message: '查询成功'
      });
    } catch (apiError) {
      console.error('查询支付宝API失败:', apiError);
      res.json({
        code: 500,
        success: false,
        message: '查询支付宝API失败',
        error: apiError.message
      });
    }
  } catch (error) {
    console.error('查询订单失败:', error);
    res.json({
      code: 500,
      success: false,
      message: '查询订单失败',
      error: error.message
    });
  }
});

/* GET home page. */
router.get('/index', async function(req, res, next) {
  let id = req.query.id
  let data = await UserModel.find({_id:id})
  res.send({
    data:data[0]
  })
});

router.post('/jia',async function(req, res, next) {
  let {id,amount} = req.body
  let data =await UserModel.find({_id:id})
  let money = data[0].money+parseFloat(amount)*10
  await UserModel.updateOne({_id:id},{money:money})

  res.send({
    code:200
  })
});
router.get('/', function(req, res, next) {
  res.render('index', { title: 'Express' });
});

// 日期格式化函数
function formatDate(date, format) {
  const o = {
    "y+": date.getFullYear(),
    "M+": date.getMonth() + 1,
    "d+": date.getDate(),
    "H+": date.getHours(),
    "m+": date.getMinutes(),
    "s+": date.getSeconds()
  };
  
  for (let k in o) {
    if (new RegExp("(" + k + ")").test(format)) {
      format = format.replace(RegExp.$1, 
        RegExp.$1.length === 1 ? o[k] : ("00" + o[k]).substr(String(o[k]).length));
    }
  }
  return format;
}

// 添加Date.format方法用于格式化日期
Date.prototype.format = function(fmt) {
  var o = {
    "M+": this.getMonth() + 1,
    "D+": this.getDate(),
    "h+": this.getHours(),
    "m+": this.getMinutes(),
    "s+": this.getSeconds(),
    "Y+": this.getFullYear()
  };
  for (var k in o) {
    if (new RegExp("(" + k + ")").test(fmt)) {
      fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
    }
  }
  return fmt;
};

// PayPal支付创建订单接口
router.post('/api/paypal/create', async (req, res) => {
  try {
    // 从请求中获取数据
    const { amount, userId } = req.body;

    if (!amount || parseFloat(amount) <= 0) {
      return res.json({
        code: 400,
        success: false,
        message: '金额无效'
      });
    }

    // 生成订单号
    const orderId = 'YC_' + Date.now() + Math.floor(Math.random() * 1000);
    const price = parseFloat(amount).toFixed(2);
    // 将人民币转换为美元 (假设汇率为1:0.14，实际应该使用实时汇率)
    const usdPrice = (parseFloat(price) * 0.14).toFixed(2);
    const name = '洋币充值';

    // 创建PayPal请求对象
    const request = new paypal.orders.OrdersCreateRequest();
    request.prefer("return=representation");
    
    // 设置PayPal订单参数
    request.requestBody({
      intent: 'CAPTURE',
      purchase_units: [{
        reference_id: orderId,
        description: name,
        custom_id: userId || '', // 透传用户ID
        amount: {
          currency_code: 'USD',  // 使用美元，PayPal支持的币种
          value: usdPrice
        }
      }],
      application_context: {
        brand_name: '洋币商城',
        landing_page: 'NO_PREFERENCE',
        user_action: 'PAY_NOW',
        return_url: 'http://localhost:5173/my',
        cancel_url: 'http://localhost:5173/my/deposit'
      }
    });

    // 调用PayPal API创建订单
    const response = await client().execute(request);
    
    // 取得批准链接(用于重定向用户到PayPal支付页面)
    const approveLink = response.result.links.find(link => link.rel === 'approve').href;
    
    res.json({
      code: 200,
      success: true,
      data: {
        orderId: orderId,
        paypalOrderId: response.result.id,
        approveLink: approveLink,
        originalAmount: price, // 原始人民币金额
        usdAmount: usdPrice    // 转换后的美元金额
      },
      message: '创建PayPal支付订单成功'
    });
  } catch (error) {
    console.error('创建PayPal支付订单失败:', error);
    res.json({
      code: 500,
      success: false,
      message: '创建PayPal支付订单失败',
      error: error.message
    });
  }
});

// PayPal支付验证订单接口
router.post('/api/paypal/capture', async (req, res) => {
  try {
    const { paypalOrderId, userId } = req.body;

    if (!paypalOrderId) {
      return res.json({
        code: 400,
        success: false,
        message: 'PayPal订单ID不能为空'
      });
    }
    
    // 创建请求对象来捕获订单
    const request = new paypal.orders.OrdersCaptureRequest(paypalOrderId);
    request.requestBody({});
    
    // 调用PayPal API捕获订单
    const response = await client().execute(request);
    
    if (response.result.status === 'COMPLETED') {
      // 支付成功，获取美元金额
      const usdAmount = parseFloat(response.result.purchase_units[0].amount.value);
      
      // 将美元金额转换回人民币金额 (使用相反的汇率转换)
      const cnyAmount = (usdAmount / 0.14).toFixed(2);
      
      // 计算获得的洋币数量 (基于人民币金额)
      const yangcoinAmount = parseFloat(cnyAmount) * 10;
      
      // 更新用户洋币余额
      if (userId) {
        try {
          await UserModel.findByIdAndUpdate(userId, { $inc: { yangcoin: yangcoinAmount } });
          console.log(`用户 ${userId} 洋币增加 ${yangcoinAmount}, PayPal支付成功`);
          
          // 保存支付记录到数据库
          // 这里可以添加交易记录的保存逻辑
        } catch (err) {
          console.error('更新用户洋币失败:', err);
        }
      }
      
      res.json({
        code: 200,
        success: true,
        data: {
          paymentId: response.result.id,
          usdAmount: usdAmount,
          cnyAmount: cnyAmount,
          yangcoinAmount: yangcoinAmount,
          status: response.result.status
        },
        message: 'PayPal支付成功'
      });
    } else {
      res.json({
        code: 400,
        success: false,
        message: '支付未完成',
        data: response.result
      });
    }
  } catch (error) {
    console.error('PayPal支付验证失败:', error);
    res.json({
      code: 500,
      success: false,
      message: 'PayPal支付验证失败',
      error: error.message
    });
  }
});

// 查询PayPal支付结果
router.get('/api/paypal/query', async (req, res) => {
  try {
    const { paypalOrderId } = req.query;

    if (!paypalOrderId) {
      return res.json({
        code: 400,
        success: false,
        message: 'PayPal订单ID不能为空'
      });
    }

    // 创建请求对象
    const request = new paypal.orders.OrdersGetRequest(paypalOrderId);
    
    // 调用PayPal API查询订单
    const response = await client().execute(request);
    
    // 提取订单状态和关键信息
    const orderStatus = response.result.status;
    const orderDetails = {
      id: response.result.id,
      status: orderStatus,
      createTime: response.result.create_time,
      updateTime: response.result.update_time
    };
    
    if (response.result.purchase_units && response.result.purchase_units.length > 0) {
      const purchaseUnit = response.result.purchase_units[0];
      orderDetails.amount = purchaseUnit.amount;
      orderDetails.referenceId = purchaseUnit.reference_id;
      
      if (purchaseUnit.payments && purchaseUnit.payments.captures) {
        orderDetails.payments = purchaseUnit.payments.captures;
      }
    }
    
    res.json({
      code: 200,
      success: true,
      data: {
        orderStatus: orderStatus,
        orderDetails: orderDetails
      },
      message: '查询成功'
    });
  } catch (error) {
    console.error('查询PayPal订单失败:', error);
    res.json({
      code: 500,
      success: false,
      message: '查询PayPal订单失败',
      error: error.message
    });
  }
});

// 头像上传接口
router.post('/uploadAvatar', function(req, res) {
  upload(req, res, async function(err) {
    if (err) {
      console.error('头像上传错误:', err);
      return res.send({
        code: 400,
        message: err.message || '头像上传失败'
      });
    }
    
    try {
      const userId = req.body.userId;
      
      if (!userId) {
        return res.send({
          code: 400,
          message: '缺少用户ID'
        });
      }
      
      if (!req.file) {
        return res.send({
          code: 400,
          message: '未选择文件'
        });
      }
      
      // 构建文件URL
      const baseUrl = `${req.protocol}://${req.get('host')}`;
      const avatarPath = '/uploads/avatars/' + req.file.filename;
      const avatarUrl = baseUrl + avatarPath;
      
      // 更新用户头像
      await UserModel.updateOne(
        { _id: userId },
        { img: avatarUrl }
      );
      
      res.send({
        code: 200,
        message: '头像上传成功',
        data: { avatarUrl }
      });
    } catch (error) {
      console.error('处理头像上传失败:', error);
      res.send({
        code: 500,
        message: '服务器错误，处理头像失败'
      });
    }
  });
});

// 用户信息更新接口
router.post('/updateUser', async function(req, res, next) {
  try {
    const { id, userName, phone, sex, age } = req.body;
    
    // 验证必填字段
    if (!id || !userName) {
      return res.send({
        code: 400,
        message: '缺少必要参数'
      });
    }
    
    // 更新用户信息
    const updateFields = {
      userName,
      phone,
      sex,
      age
    };
    
    // 过滤掉未定义的字段
    Object.keys(updateFields).forEach(key => {
      if (updateFields[key] === undefined) {
        delete updateFields[key];
      }
    });
    
    // 执行更新
    await UserModel.updateOne({ _id: id }, updateFields);
    
    res.send({
      code: 200,
      message: '用户信息更新成功'
    });
  } catch (error) {
    console.error('更新用户信息失败:', error);
    res.send({
      code: 500,
      message: '服务器错误，更新失败'
    });
  }
});

// 获取用户动态接口
router.get('/getUserDynamics', async function(req, res, next) {
  try {
    const { userId } = req.query;
    
    if (!userId) {
      return res.send({
        code: 400,
        message: '缺少用户ID'
      });
    }
    
    // 查询用户的动态并按时间降序排序
    const dynamics = await Dynamics.find({ user_id: userId })
      .sort({ time: -1 })
      .populate('user_id', 'userName img'); // 关联查询用户信息
    
    res.send({
      code: 200,
      data: dynamics,
      message: '获取用户动态成功'
    });
  } catch (error) {
    console.error('获取用户动态失败:', error);
    res.send({
      code: 500,
      message: '服务器错误，获取失败'
    });
  }
});

module.exports = router;